package com.opennetexam.manager.socket;

import com.opennetexam.manager.socketfactory.SocketFactory;
import com.opennetexam.manager.socketfactory.SocketServerBusinessProcess;
import com.opennetexam.manager.utils.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description webSocket_server
 * @Author 奶茶
 * Created by on 2018/10/5 16:24.
 */
@Component
@ServerEndpoint("/socket/takePhoto")
public class WebSocketServer {

    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    //用来记录当前在线连接数
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    //线程安全的WebSocket集合 用来存放每个客户端对应的WebSocket对象
    private static CopyOnWriteArraySet<WebSocketServer> webSocketServers = new CopyOnWriteArraySet<WebSocketServer>();

    //与某个客户端的链接会话  用来给客户端发送消息
    private Session session;


    /**
     * 连接建立成功调用的方法
     * @param session
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketServers.add(this);
        addOnlineCount();
        logger.info("新链接加入，当前连接数为：" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketServers.remove(this);
        subOnlineCount();
        logger.info("当前链接关闭，当前连接数为：" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     * */
    @OnMessage(maxMessageSize = 1000000)
    public void onMessage(String message, Session session) {
        logger.info("-------------------接收来自客户端消息------------------");
        Map<String, Object> map = GsonUtil.fromJsonToMap(message);
        //根据客户端的请求类别做相关操作
        SocketServerBusinessProcess socketServerBusinessProcess = SocketFactory.newInstance(Integer.valueOf(map.get("type").toString()));
        if(socketServerBusinessProcess != null){
            socketServerBusinessProcess.socketServerBusinessProcess(map);
        }
    }

    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (WebSocketServer item : webSocketServers) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                logger.error("群发消息异常！",e);
            }
        }
    }

    /**
     * 发生错误时调用
     */
     @OnError
     public void onError(Session session, Throwable error) {
        logger.error("发生错误",error);
     }

    /**
     * 发送消息
     * @param message
     */
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    private static AtomicInteger getOnlineCount() {
        return onlineCount;
    }

    private static void addOnlineCount() {
        WebSocketServer.onlineCount.getAndIncrement();
    }

    private static void subOnlineCount() {
        WebSocketServer.onlineCount.getAndDecrement();
    }

}
